
const App = getApp()

//网络请求封装
import Request_post from "../../../../request/Request_post"
import Request_get from "../../../../request/Request_get"

//系统设置项目:(请求地址-在封装中已经引入，这里不需要;   api调用的Appid-partner_app_id;   渠道ID-as_appid)
import config from '../../../../config/config'; 

// 缓存rul图片到本地
import cacheimg from "../../../../utils/cacheImg"

// 获取微信扫一扫URL中的参数 https://www.mp.kmabacus.com/coupon?id=123&des=abc :   获取 123 及 abc
let utils = require("../../../../utils/CustomFunction/getQueryString.js")

Page({

  /**
   * 页面的初始数据
   */
  data: {

    // loading组件加载显示
    loadingShow: true,

    // 是否显示骨架屏
    skeletonloading: true,


    // 页面外链资源图片（需要本地缓存的）
    Title_Image: 
    [ 
      {key: "Title_Image",value: config.imageUrl+"title_member_Cop_Center.jpg"},
    ],


    // 页面外链资源图片（需要本地缓存的）
    pageImage: 
    [ 
      {key: "Title_Image",value: config.imageUrl+"title_member_Cop_Center.jpg"},
      {key: "back_home",value: config.imageUrl+"back_home.png"},
      {key: "mine_cop",value: config.imageUrl+"mine_cop.png"},
      {key: "scan_cop",value: config.imageUrl+"scan_cop.png"},
      {key: "get_cop",value: config.imageUrl+"get_cop.png"},
      {key: "itg_cop",value: config.imageUrl+"itg_cop.png"},
      {key: "pay_cop",value: config.imageUrl+"pay_cop.png"},
    ],

    //优惠券中心功能
    cop_funlist:[
      {name:"免费领取",details:"会员福利免费领取",imgurl:config.imageUrl+"get_cop.png",linkurl:"/SubpkgMarketing/pages/Coupon/IssueCopList/IssueCopList?echmodid="+"02"+'&index=0'},
			{name:"扫码领券",details:"扫描二维码领取",imgurl:config.imageUrl+"scan_cop.png",linkurl:"/pages/Member/member_Coupon/member_Cop_ScanCode_Get/member_Cop_ScanCode_Get"},
      {name:"积分兑券",details:"会员积分兑换券",imgurl:config.imageUrl+"itg_cop.png",linkurl:"/SubpkgMarketing/pages/Coupon/IssueCopList/IssueCopList?echmodid="+"06"+'&index=0'},
      {name:"秒杀购券",details:"超低折扣购买券",imgurl:config.imageUrl+"pay_cop.png",linkurl:"/SubpkgMarketing/pages/Coupon/IssueCopList/IssueCopList?echmodid="+"05"+'&index=0'}
    ],

    // Vant: tabbar(当前选中标签的索引,本页面索引 == 0) 本页面的tabbar只有通过停车缴费页面链接进入才会显示
    active: 2,

    // 是否是从停车缴费页面链接过来的 默认：flase-不是；true-是
    fromPkvPage:false


  },

  /** 普通Title && 带动画Title 设置 */
  titleImageSetup:function(){
    var that = this
    let obj = {}
    let pageimgArr = that.data.Title_Image
    // 数组转换为对象
    pageimgArr.forEach(i => {obj[i.key] = i.value})
    that.setData({background_image: obj })
    // console.log(that.data.background_image)
  },

  /** 外链图片Url资源，缓存到本地 */
	storeImage:function(){
    var that = this
    let obj = {}
    let pageimgArr = that.data.pageImage
    // 图片外链url：ip:端口 替换成 域名（外链资源不做域名转换了，而是外链资源原始链接必须就是域名url）
    // pageimgArr.forEach(i => {i.value = config.domainName + i.value.split('/').slice(3).join('/')})
    // 调用本地文件缓存方法 mapCacheUrl
    pageimgArr = pageimgArr.map(i => ({
      ...i,imgpath:cacheimg.mapCacheUrl(i.value)
    }))  
    // 数组转换为对象
    pageimgArr.forEach(i => {obj[i.key] = i.imgpath})
    that.setData({pageStoreimg: obj})
    console.log(that.data.pageStoreimg)
  },
  

  /** 扫码领取优惠券 */
  scanCode:function(){
    var that = this
    wx.scanCode({   //调用微信扫一扫
      onlyFromCamera:true,
      scanType:['qrCode','barCode'],
      success: (res) => {
        if(res.errMsg == "scanCode:ok"){
          that.setData({
            QR_CODE:res.result
          })
          let q = decodeURIComponent(that.data.QR_CODE);
          //解析二维码中的参数值
          if (that.data.QR_CODE){
            that.setData({
              rulechbllno: utils.getQueryString(q,'rulechbllno'),
              copcltid: utils.getQueryString(q,'echcltid')
            })
          }
          console.log("小程序内部扫一扫获取的参数：",that.data.rulechbllno,that.data.copcltid)
          // 优惠券秒杀-echcopseckill 秒杀下单
          let bllno = App.globalData.mbrid + Math.round(new Date() / 1000)	// 在线充值单单号：mbrid+时间戳
          let mbrparams = wx.getStorageSync('StrMbrInfo').mbrparams
          that.setData({bllno,mbrparams})
          Request_post.post(
            config.domainName+"api_echcopseckill/buycopseckill",
            {
              bllno: that.data.bllno,
              rulechbllno: that.data.rulechbllno,           //微信扫一扫获取到的参数：规则单号
              echmodid: "01",
              qty: 1,
              mbrparams: that.data.mbrparams
            },
            function(res){
              if(res != 'undefined' && res.return_no == 1){
                console.log('秒杀下单成功：回调信息存缓存',res)
                // 秒杀下单成功：回调信息存缓存
                wx.setStorageSync('StrCopseckillodr',res.return_data)

                /* Api请求：优惠券服务-echcopsrv 001-扫码领券 */
                Request_post.post(
                  config.domainName+"api_echcopsrv/scnechcop",
                  {
                    srcbllno: that.data.bllno,
                    copcltid: that.data.copcltid,
                    echtmnid: config.echtmnid,
                    rulechbllno: that.data.rulechbllno,       //微信扫一扫获取到的参数：规则单号
                    mbrparams:	that.data.mbrparams
                  },
                  function(res){
                    if(res != "undefined" && res.return_no == 1){
                      that.setData({
                        msg:res.return_msg,
                        copid:escape(res.return_data.copid)
                      })
                      wx.redirectTo({
                        url:"/SubpkgMarketing/pages/Coupon/GetCopSuccess/GetCopSuccess?copid="+that.data.copid+"&msg="+that.data.msg
                      })	
                    }else{
                      // 获取券失败：取消秒杀下单
                      that.CancelBuycopOdr();
                      that.setData({
                        msg:res.return_msg,
                      })
                      wx.redirectTo({
                        url:"/SubpkgMarketing/pages/Coupon/GetCopFailed/GetCopFailed?msg="+that.data.msg
                      })
                    }
                  }
                )
              }else{
                wx.showModal({
                  content: res.return_msg,
                  showCancel: false,		//是否显示取消按钮
                  confirmText:"确认",		//默认是“确定”
                  confirmColor: 'skyblue',	//确定文字的颜色  
              })
              }
            }
          )

        }
      }

    })
  },

  // 路由到我的券包
  navigator_mineCop:function(){
    wx.navigateTo({
      url: '/SubpkgMarketing/pages/Coupon/MineCopList/MineCopList',
    })
  },

  // 回到首页
  backHome:function(){
    wx.redirectTo({
      url: App.globalData.homePage,
    })
  },


  //未注册会员点击注册
  regNow:function(){
    wx.redirectTo({ 
      url:"/SubpkgPublicPage/pages/PublicPage/PrivacyPolicy/PolicyMain/PolicyMain"
    });
  },

  // tabbar 选中事件 (本页面的：active == 2)
  onChange(event) {
    this.setData({ active: event.detail });
    if(this.data.active == 1){
      wx.navigateTo({
        url:"/SubpkgParkingPay/pages/ParkingPublic/pkvfeequeryList/pkvfeequeryList"
      })
    }
    else if(this.data.active == 0){
      wx.navigateTo({
        url:"/SubpkgParkingPay/pages/ParkingPublic/NumberPlate/NumberPlate",
      })
    }
    else if(this.data.active == 3){
      if(App.globalData.miniProgram_appid == 'wx2e4f358a20d4a419'){   //昭通金池小程序：wx2e4f358a20d4a419
        wx.navigateToMiniProgram({
          appId: 'wx54b2f86f6aecfdff',
          path: '/pages/home/dashboard/index',
          success(res) {
            console.log(res)
          }
        })
      }else{
        wx.redirectTo({
          url:App.globalData.homePage,
        })
      }

		}

  },



  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    if(options.fromPkvPage){
      that.setData({
        fromPkvPage: options.fromPkvPage
      })
    }
    // 昭通金池定制跳转
    if(App.globalData.miniProgram_appid == 'wx2e4f358a20d4a419'){   //昭通金池小程序：wx2e4f358a20d4a419
      this.setData({tabbartext:'西苑汇'})
    }else{
      this.setData({tabbartext:'返回首页'})
    }

    

    // 会员是否注册的标志regflg
    getApp().loginPromise.then(v => {	//app.js的Promise成功回调（全局变量赋值成功后才执行请求）
      this.setData({regflg: App.globalData.regflg})
      // console.log(App.globalData.regflg)
    })
    
    that.setData({
      PageBackgroundImageEffects: wx.getStorageSync('StrMktopt').PageBackgroundImageEffects,  // 页面背景图： 01-无特效-原图；02-静态特效-CSS下边内弧；03-动态特效-波浪动态特效
      DynamicColorGradient: wx.getStorageSync('StrMktopt').DynamicColorGradient               // 颜色动态渐变
    })
    




    // 调用页面Title图片的设置方法
    that.titleImageSetup()
    
    // 外链资源图片链接 本地缓存
    if(App.globalData.ResourcesLink_Locstr === 'y'){
      that.storeImage();
    // 外链资源图片链接 直接读取url地址
    }else{
      let pageimgArr = that.data.pageImage
      let object = {}
      pageimgArr.forEach(i => {object[i.key] = i.value}) // 数组转换为对象
      that.setData({
        pageStoreimg: object
      })
      // console.log(that.data.pageStoreimg)
		}

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

    var that = this
    //缓存数组，页面使用数组（优惠券中心功能列表）
    var array = that.data.cop_funlist

    if(App.globalData.Erpimage_Locstr ==='y'){
      for(var i in array){
        if(array[i].imgurl){
          array[i].imgurl = config.domainName + array[i].imgurl.split('/').slice(3).join('/');
        }
      }
      that.setData({
        cop_funlist:array.map(i => ({
          ...i,
          imgpath:cacheimg.mapCacheUrl(i.imgurl)
        }))  
      }) ;
      that.Delay();
    }else{
      that.setData({
        cop_funlist:array.map(i => ({
          ...i,
          imgpath: i.imgurl
        }))  
      }) ;
      that.Delay();
    }

  },

  // 延时处理
  Delay:function(){
    var that = this
    setTimeout(function(){
      //延迟要处理的事物
      that.setData({
        skeletonloading: false,
        loadingShow: "false"
      })
    },1500)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})